package com.example.cardserver.controller;


import com.alibaba.fastjson.JSON;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.cardserver.entity.IdCard.IdCardDataType;
import com.example.cardserver.entity.IdCard.IdCardRoot;
import com.example.cardserver.entity.User;
import com.example.cardserver.service.IUserService;
import com.example.cardserver.service.ex.UserException;
import com.example.cardserver.util.Base64ToMultipartFile;
import com.example.cardserver.util.JsonResult;
import lombok.SneakyThrows;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("user")
@RestController
public class UserController extends BaseController{
    @Resource
    private IUserService userService;
    
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("findp")
    public JsonResult<User> find(String phone){
        User user = userService.getByPhone(phone);
        return new JsonResult<>(OK, user);
    }

    @RequestMapping("ping")
    public JsonResult<Void> ping(){
        return new JsonResult<>(OK);
    }
    
    
//    public static MultipartFile base64ToMF(String string64){
//        String regex = "data:image/(.*?);base64";
//        if(StrUtil.isBlank(string64)){
//            return null;
//        }
//        String type = getSubUtilSimple(string64, regex);
//        string64 = string64.replaceFirst("data:(.+?);base64","");
//        byte[] imageByte;
//        String filename = "";
//        imageByte = Base64.decode(string64.replaceAll(" ","+"));
//        filename = UUID.randomUUID().toString() + "." + type;
//        
//        InputStream inputStream = new ByteArrayInputStream(imageByte);
//        MockMultipartFile mockMultipartFile = null;
//        try{
//            mockMultipartFile = new MockMultipartFile(filename, filename, "", inputStream);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return mockMultipartFile;
//    }
//    
//    public static String getSubUtilSimple(String soap, String regex){
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(soap);
//        while(matcher.find()){
//            return matcher.group(1);
//        }
//        return "";
//    }

    public static boolean decryptByBase64(String base64, String filePath) {
        if (base64 == null && filePath == null) {
            return false;
        }
        try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
    @RequestMapping(value = "base64test", method = RequestMethod.POST)
    public JsonResult<String> fileTest(@RequestBody String string){
//        decryptByBase64(string, "E:\\TEST\\temp.jpg");
//        return new JsonResult<Void>(OK);
        System.out.println(string);
        return new JsonResult<>(OK, string);
    }
    
    public static MultipartFile base64ToMF(String string64){
        MultipartFile multipartFile = new Base64ToMultipartFile(string64, "jpeg", "image/jpeg");
        return multipartFile;
    }
    
    
    @RequestMapping(value = "recg", method = RequestMethod.POST)
    public JsonResult<Object> recognize(@RequestBody String string){
        //System.out.println(string);
        string = string.replaceAll("\\s+","");
        MultipartFile multipartFile = base64ToMF(string);
        return new JsonResult<>(OK, ocr(multipartFile));
    }

    @RequestMapping(value = "regg", method = RequestMethod.POST)
    public JsonResult<Void> regg(String phone, String password, String commentCode, String code, String bonus){
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setCommentCode(commentCode);
        user.setBalance(0);
        user.setCode(code);
        user.setSchedule(0);
        userService.getBonus(bonus);
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping(value = "regh", method = RequestMethod.POST)
    public JsonResult<Void> regh(String password, String commentCode, String code, String bonus){
        User user = new User();
        user.setPassword(password);
        user.setCommentCode(commentCode);
        user.setBalance(0);
        user.setCode(code);
        user.setSchedule(0);
        //userService.getBonus(bonus);
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    public static com.aliyun.ocr_api20210707.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }
    
    @SneakyThrows
    @RequestMapping("ocr")
    public static Object ocr(@RequestParam("file")MultipartFile file){
        com.aliyun.ocr_api20210707.Client client = UserController.createClient
                ("", "");
        InputStream bodySyream = file.getInputStream();
        com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = 
                new RecognizeIdcardRequest().setBody(bodySyream);
        RuntimeOptions runtime = new RuntimeOptions();
        try{
            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
            RecognizeIdcardResponseBody body = response.getBody();
            String data = body.getData();
            //System.out.println(data);
            IdCardRoot idCardRoot = JSON.parseObject(data, IdCardRoot.class);
            //System.out.println(idCardRoot);
            return idCardRoot;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
//    @RequestMapping("login")
//    public JsonResult<User> login(String phone, String password, HttpSession session){
//        User data = userService.login(phone, password);
//        session.setAttribute("id", data.getId());
//        session.setAttribute("phone", data.getPhone());
//        return new JsonResult<User>(OK, data);
//    }

    @RequestMapping("login")
    public JsonResult<User> login(String code, String pwd){
        User data = userService.login(code, pwd);
        if(data!=null)
            return new JsonResult<User>(OK, data);
        else return new JsonResult<>(ERR);
    }
    
    @RequestMapping("/change_password")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session){
        Integer id = getIdFromSession(session);
        String phone = getPhoneFromSession(session);
        userService.changePassword(id, phone, oldPassword, newPassword);
        return new JsonResult<>(OK);
    }

    public static final int AVATAR_MAX_SIZE = 10 *1024 * 1024;
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file")MultipartFile file){
        if(file.isEmpty()){
            throw new UserException("未选择文件");
        }
        if(file.getSize() > AVATAR_MAX_SIZE){
            throw new UserException("文件大小超出限制");
        }
        String type = file.getContentType();
        if(!AVATAR_TYPE.contains(type)){
            throw new UserException("文件类型不支持");
        }
        String parent = session.getServletContext().getRealPath("upload");
        //让FIle对象指向这个路径,FIle是否存在
        File dir = new File(parent);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //获取文件名后用UUID的方式存储
        String originalFilename = file.getOriginalFilename();
        System.out.println("OriginalFilename"+originalFilename);
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+ suffix;
        //此时创建了一个空文件
        File dist = new File(dir,filename);
        //将参数file中的数据写入到这个空文件中
        try {
            file.transferTo(dist);
        } catch (IOException e){
            throw new UserException("文件读写异常");
        } catch (UserException e){
            throw new UserException("文件状态异常");
        }
        Integer id = getIdFromSession(session);
        String avatar = "/upload"+filename;
        userService.changeAvatar(id, avatar);
        return new JsonResult<>(OK,avatar);
    }
    
}
